package com.guigu.controller;


import com.guigu.pojo.OrderPayment;
import com.guigu.pojo.PurchaseOrder;
import com.guigu.pojo.PurchaseOrderDetails;
import com.guigu.service.OrderPaymentService;
import com.guigu.service.PurchaseOrderDetailsService;
import com.guigu.service.PurchaseOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.pojo.PurchaseOrder;
import com.guigu.service.PurchaseOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 采购单表 前端控制器
 * </p>
 *
 * @author Mr.Zhang
 * @since 2025-03-12
 */
@CrossOrigin
@RestController
@RequestMapping("/purchase-order")
public class PurchaseOrderController {

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private PurchaseOrderDetailsService purchaseOrderDetailsService;

    @Autowired
    private OrderPaymentService orderPaymentService;

    // 生成订单号（long 类型）
    private static String date;
    private static long orderNum = 0L;

    public static synchronized long getOrderNo() {
        String str = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
        if (date == null || !date.equals(str)) {
            date = str;
            orderNum = 0L;
        }
        orderNum++;
        long orderNO = Long.parseLong(date) * 10000;
        orderNO += orderNum;
        return orderNO;  // 返回 long 类型订单号
    }

    @PostMapping("/addPurchaseOrder")
    @ResponseBody
    public boolean addPurchaseOrder(@RequestBody ArrayList<Object> data) {
        System.out.println(data);
        Boolean a = false;
        Boolean b = false;
        for (Object list : data) {
            HashMap<String, Object> map = (HashMap<String, Object>) list;
            Integer supplierId = Integer.valueOf(Integer.parseInt(map.get("supplierId").toString()));
            PurchaseOrder purchaseOrderBySupplierId = purchaseOrderService.getPurchaseOrderBySupplierId(supplierId);
            if(purchaseOrderBySupplierId == null) {
                PurchaseOrder purchaseOrder = new PurchaseOrder();
                long orderNoLong = getOrderNo();  // long 类型订单号
                String orderNoString = String.valueOf(orderNoLong);  // 转换为 String 类型存储在数据库
                purchaseOrder.setPurchaseOrderNumber(orderNoString);
                purchaseOrder.setSupplierId(supplierId);
                purchaseOrder.setTotalAmount(Integer.valueOf(Integer.parseInt(map.get("count").toString())));
                Float price = Float.valueOf(Float.parseFloat(map.get("price").toString()));
                purchaseOrder.setTotalPrice(price * Integer.valueOf(Integer.parseInt(map.get("count").toString())));
                purchaseOrder.setRegister("管理员");
                purchaseOrder.setRegisterTime(new Date());
                purchaseOrder.setPayMethod("P002-1");
                purchaseOrder.setChecker("");
                purchaseOrder.setCheckTime(new Date());
                purchaseOrder.setCheckReason("");

                a = purchaseOrderService.save(purchaseOrder);

                PurchaseOrderDetails purchaseOrderDetails = new PurchaseOrderDetails();
                purchaseOrderDetails.setPurchaseId(purchaseOrder.getPurchaseId());
                purchaseOrderDetails.setProductId(Integer.valueOf(Integer.parseInt(map.get("productId").toString())));
                purchaseOrderDetails.setCount(Integer.valueOf(Integer.parseInt(map.get("count").toString())));
                purchaseOrderDetails.setPrice(price);
                purchaseOrderDetails.setSubtotal(price * Integer.valueOf(Integer.parseInt(map.get("count").toString())));
                b = purchaseOrderDetailsService.save(purchaseOrderDetails);

            }else {
                purchaseOrderBySupplierId.setTotalAmount(purchaseOrderBySupplierId.getTotalAmount() + Integer.valueOf(map.get("count").toString()));
                purchaseOrderBySupplierId.setTotalPrice(purchaseOrderBySupplierId.getTotalPrice() + Float.valueOf(map.get("price").toString()) * Integer.valueOf(map.get("count").toString()));
                a = purchaseOrderService.updateById(purchaseOrderBySupplierId);

                PurchaseOrderDetails purchaseOrderDetails = new PurchaseOrderDetails();
                purchaseOrderDetails.setPurchaseId(purchaseOrderBySupplierId.getPurchaseId());
                purchaseOrderDetails.setProductId(Integer.valueOf(Integer.parseInt(map.get("productId").toString())));
                purchaseOrderDetails.setCount(Integer.valueOf(Integer.parseInt(map.get("count").toString())));
                purchaseOrderDetails.setPrice(Float.valueOf(Float.parseFloat(map.get("price").toString())));
                purchaseOrderDetails.setSubtotal(Float.valueOf(Float.parseFloat(map.get("price").toString())) * Integer.valueOf(Integer.parseInt(map.get("count").toString())));
                b = purchaseOrderDetailsService.save(purchaseOrderDetails);

            }
        }
        if(a == true && b == true){
            return true;
        }else{
            return false;
        }
    }



    //显示审核页面
    @PostMapping("/purchaseReview")
    @ResponseBody
    public List<PurchaseOrder> purchaseReview(@RequestBody HashMap<String, Object> map) {
        List<PurchaseOrder> paurchaseReview = purchaseOrderService.getPurchaseReview(map);
        System.out.println(paurchaseReview);
        if (paurchaseReview != null) {
            return paurchaseReview;
        }
        return null;
    }

    //审核
    @PostMapping("/review")
    @ResponseBody
    public boolean review(@RequestBody HashMap<String, Object> map) {
        String purchaseOrderNumber = map.get("purchaseOrderNumber").toString();
        System.out.println(purchaseOrderNumber);
        PurchaseOrder purchaseOrder = purchaseOrderService.getPurchaseOrderBypurchaseOrderNumber(purchaseOrderNumber);
        purchaseOrder.setChecker(map.get("reviewer").toString());
        purchaseOrder.setCheckTime(new Date());
        purchaseOrder.setCheckReason(map.get("reason").toString());
        purchaseOrder.setCheckTag("S001-3");
        System.out.println(purchaseOrder);
        OrderPayment orderPayment = new OrderPayment();
        orderPayment.setOrderId(purchaseOrderNumber);
        orderPayment.setPaymentMethod("P002-1");
        orderPayment.setPaymentAmount(purchaseOrder.getTotalPrice());
        orderPayment.setPaymentTime(new Date());
        orderPayment.setPaymentStatus("K002-3");

        boolean save = orderPaymentService.save(orderPayment);

        boolean b = purchaseOrderService.saveOrUpdate(purchaseOrder);
        if (b && save) {
            return true;
        }
        return false;
    }

    //拒绝审核
    @GetMapping("/{purchaseOrderNumber}")
    @ResponseBody
    public boolean noReview(@PathVariable String purchaseOrderNumber) {
        PurchaseOrder purchaseOrder = purchaseOrderService.getPurchaseOrderBypurchaseOrderNumber(purchaseOrderNumber);
        System.out.println(purchaseOrder);
        purchaseOrder.setCheckTag("S001-2");

        boolean b = purchaseOrderService.saveOrUpdate(purchaseOrder);
        if (b) {
            return true;
        }
        return false;
    }

    //查询所有采购单列表
    @PostMapping("/selectAllPurchaseOrder")
    @ResponseBody
    public List<PurchaseOrder> selectAllPurchaseOrder(@RequestBody HashMap<String, Object> map){
        List<PurchaseOrder> purchaseOrders = purchaseOrderService.selectAllPurchaseOrder(map);

        System.out.println(purchaseOrders);
        return purchaseOrders;
    }


    @PostMapping("/getSupplierOrderBySupplierId")
    @ResponseBody
    public Page<PurchaseOrder> getSupplierOrderBySupplierId(Integer supplierId, Integer currentPage, Integer pageSize  ){
        return purchaseOrderService.getSupplierOrderBySupplierId(supplierId,currentPage,pageSize);
    }

    @PostMapping("/shipping")
    @ResponseBody
    public boolean shipping(Integer purchaseId){
        PurchaseOrder purchaseOrder = purchaseOrderService.getById(purchaseId);
        purchaseOrder.setConveyTag("P001-2");
        return purchaseOrderService.updateById(purchaseOrder);
    }

    @GetMapping("/getSupplierOrderCountBySupplierId")
    @ResponseBody
    public Integer getSupplierOrderCountBySupplierId(Integer supplierId){
        return purchaseOrderService.getSupplierOrderCountBySupplierId(supplierId);
    }

}

